/**
 * 课程数据管理
 */

import { CourseScheduleResponse, CourseScheduleData, Course } from '../types/course';

/**
 * 从JSON文件加载课程数据
 * @returns 完整的API响应数据
 */
export const loadCourseData = async (): Promise<CourseScheduleResponse> => {
  const response = await fetch('/new_course_schedule.json');
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = await response.json();
  return data as CourseScheduleResponse;
};

/**
 * 验证单个课程数据的完整性
 * @param course 课程数据
 * @returns 是否有效
 */
export const validateCourse = (course: any): course is Course => {
  const requiredFields = [
    'course_name',
    'section',
    'day_of_week',
    'weeks',
    'location',
    'teacher'
  ];

  return requiredFields.every(field => {
    const value = course[field];
    if (value === undefined || value === null) return false;

    if (field === 'teacher' || field === 'location' || field === 'section' || field === 'weeks') {
      return typeof value === 'object' && Object.keys(value).length > 0;
    }

    if (field === 'day_of_week') {
      return typeof value === 'number' && value >= 0 && value <= 7; // 0=未知, 1-7=周一至周日
    }

    return true;
  });
};

/**
 * 清理和标准化课程数据
 * @param response 原始API响应
 * @returns 清理后的课程数据，如果数据无效则返回null
 */
export const sanitizeCourseData = (response: CourseScheduleResponse): CourseScheduleData | null => {
  if (response.code !== 200 || !response.data) {
    console.error('API response error:', response.message);
    return null;
  }

  const { class_info, courses } = response.data;

  if (!class_info || !Array.isArray(courses)) {
    console.error('Invalid data structure in API response');
    return null;
  }

  const validCourses = courses.filter(course => {
    const isValid = validateCourse(course);
    if (!isValid) {
      console.warn('Invalid course data, skipping:', course);
    }
    return isValid;
  });

  return {
    class_info,
    courses: validCourses
  };
};
